<script setup lang="ts" name="DictionaryManager">
import {ref, reactive, onActivated} from 'vue'
import {HeaderData, Operation as Opr} from '@/components/dTable/dTable'
import {OperButton, SearchFromItem, SearchButton} from '@/components/dTable/dHeader'
import {PageConfig, defaultPage, defaultPageSize, defaultPageSizes, defaultLayout} from '@/components/dTable/dFooter'
import dTablePromote from '@/components/dTable/dTablePromote.vue'
import dHeader from '@/components/dTable/dHeader.vue'
import pageContainer from '@/components/pageContainer.vue'
import operation from '@/components/dTable/components/operation.vue'
import popUp from './popup.vue'
import configureDictionary from './configureDictionary.vue'
import {ElMessage, ElMessageBox, FormRules} from 'element-plus'
import {getDictionaries, getDictItem, delDict, addDictItemDatas, SearchDates, DictData, SearchRoleFromData} from '@/api/baseSetting/dictionaryManager'
import {ColorTheme, ColorRed} from '@/api/config'

// 操作栏配置项
const operationData: Array<Opr> = [
  {
    code: 'edit',
    label: '编辑',
    iconConfig: {icon: 'common-edit', type: 'custom', color: ColorTheme, size: 20}
  },
  // {
  //   code: 'dictionaries',
  //   label: '配置字典',
  //   iconConfig: {
  //     icon: 'common-maintain',
  //     type: 'custom',
  //     color: ColorTheme,
  //     size: 20
  //   }
  // },
  {
    code: 'del',
    label: '删除',
    iconConfig: {icon: 'common-delete', type: 'custom', color: ColorRed, size: 20}
  }
]

const showLoading = ref(false)
//左侧数据
const tableData = ref<Array<SearchDates>>([])

//右侧数据
const rightTableData = ref<Array<addDictItemDatas>>([])

//默认选中
const defualtSeleted = ref<SearchDates | undefined>(undefined)

// 弹窗查询id
const ID = ref<string>('')

// 弹窗显示
const showDialog = ref(false)

// 字典弹窗显示
const dictionarieShow = ref(false)


const dictCode = ref('')

//表格数据
const tableHeaderData = ref<Array<HeaderData>>([
  {
    prop: 'id',
    label: '类型编码',
    columnType: 'text',
    align: 'left',
    'min-width': '235'
  },
  {
    prop: 'pid',
    label: '类型级别',
    columnType: 'text',
    align: 'left',
    'min-width': '235'
  },
  {
    prop: 'name',
    label: '类型名称',
    columnType: 'text',
    align: 'left',
    'min-width': '297'
  },
  {
    prop: 'operation',
    label: '操作',
    columnType: 'slot',
    'width': '120',
    fixed: 'right'
  }
])

//表格数据
const tableHeaderData2 = ref<Array<HeaderData>>([
  {
    prop: 'sort',
    label: '排序号',
    columnType: 'text',
    align: 'left',
    'width': '80'
  },
  {
    prop: 'name',
    label: '类型子项名称',
    columnType: 'text',
    align: 'left',
    'min-width': '150'
  },
  {
    prop: 'id',
    label: '值',
    columnType: 'text',
    align: 'left',
    'min-width': '50'
  }
])
const popData = reactive<DictData>({
  classIndex: '',
  dictIndex: '',
  dictCode: '',
  dictName: '',
  dictItemCode: '',
  dictItemName: '',
  dictType: '',
  id: '',
  typeCode: '', //字典分类编码
  name:'',
  pid:''
})

const searchData = reactive<any>({
  pageNo: 1, // 默认页码
  pageSize: 10, // 默认每页条数
  pid: '', // 字典编码
  name: '' // 字典名称
})

//底部
const pageConfig = ref<PageConfig>({
  currentPage: defaultPage,
  pageSize: defaultPageSize,
  pageSizes: defaultPageSizes,
  total: 0,
  disabled: false,
  layout: defaultLayout
})

// 查询子项
const IfdictItem = (id: string) => {
  // showLoading.value = true
  getDictItem({id: id}).then((res) => {
    showLoading.value = false
    rightTableData.value = res.data.data
  }).catch((error) => {
    showLoading.value = false
    console.warn(error)
  })
}
const searchFromData = reactive<any>({
  pid: '',
  name: ''
})
// 字典分页查询
const Dictionaries = (resetPage?: boolean) => {
  if (resetPage) pageConfig.value.currentPage = 1
  searchData.pageSize = pageConfig.value.pageSize
  searchData.pageNo = pageConfig.value.currentPage
  searchData.pid = searchFromData.pid ? searchFromData.pid : null
  searchData.name = searchFromData.name ? searchFromData.name : null
  getDictionaries(searchData).then((res) => {
    const {data} = res.data
    data.list?.map((item) => {
      item.operation = operationData
    })
    tableData.value = data.list
    if (!tableData.value.length) {
      defualtSeleted.value = undefined
      rightTableData.value = []
    } else {
      defualtSeleted.value = tableData.value[0]
    }
    console.log('pageConfig.value.total', res.data.data.length)

    pageConfig.value.total =  res.data.data.total === null ? 0 :  res.data.data.total
  })
}
// 删除接口
const setdelDict = (id: string, code: string) => {
  delDict(id).then((res) => {
    ElMessage({
      type: 'success',
      message: '删除成功'
    })
    Dictionaries(true)

  })
}

//行点击回调
const onRowClick = (row) => {
  if (row === null) return
  IfdictItem(row.id)
}

//表头
const operButtons = ref<Array<OperButton>>([
  {
    label: '新增',
    type: 'noraml',
    iconConfig: {icon: 'common-add', type: 'custom'},
    code: 'add'
  }
])
// 筛选区功能
const searchFromItems = ref<Array<SearchFromItem>>([
  // {
  //   label: '类别等级',
  //   placeholder: '请输入类别等级',
  //   type: 'input',
  //   prop: 'pid',
  //   enterSubmit: true
  // },
  {
    label: '类别名称',
    placeholder: '请输入类别名称',
    type: 'input',
    prop: 'name',
    enterSubmit: true
  }
])


const searchFromRules = reactive<FormRules>({
  pid: [
    {
      required: false,
      message: '长度应不超过50个字符',
      max: 50,
      trigger: ['change', 'blur']
    }
  ],
  name: [
    {
      required: false,
      message: '长度应不超过50个字符',
      max: 50,
      trigger: ['change', 'blur']
    }
  ]
})

// 按钮搜索配置
const serachButtons = ref<Array<SearchButton>>([
  {type: 'search'},
  {type: 'clear'}
])
const onSubmit = () => {
  searchData.dictCode = searchFromData.dictCode
  searchData.dictName = searchFromData.dictName
  searchData.typeCode = searchFromData.typeCode
  Dictionaries(true)
}

// 操作栏点击事件
const onErtion = (err, row) => {
  switch (err) {
  case 'del':
    ElMessageBox.confirm('确认删除：' + row.name + '类型', '删除确认', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      setdelDict(row.id, row.dictCode)
    }).catch((error) => {
      console.warn(error)
    })
    break
  case 'edit':
    showDialog.value = true
    // popData.dictCode = row.dictCode
    // popData = row
    popData.name = row.name
    popData.pid = row.pid
    popData.id = row.id
    break
  case 'dictionaries':
    ID.value = row.id
    dictCode.value = row.dictCode
    dictionarieShow.value = true
    break
  }
}

const onFormClear = () => {
  searchData.dictCode = ''
  searchData.dictName = ''
  searchData.typeCode = ''
  Dictionaries(true)
}

const onOperation = () => {
  popData.dictCode = ''
  popData.dictName = ''
  popData.classIndex = ''
  popData.dictIndex = ''
  popData.id = ''
  showDialog.value = true
}

const onSizeChange = () => {
  searchData.limit = pageConfig.value.pageSize
  Dictionaries()
}

const onCurrentChange = () => {
  searchData.page = pageConfig.value.currentPage
  Dictionaries()
}

// 弹窗取消
const onCancel = () => {
  showDialog.value = false
}

// 弹窗关闭
const onClose = () => {
  showDialog.value = false
}

// 弹窗保存
const onConfirm = () => {
  showDialog.value = false
  Dictionaries()
}

// 弹窗取消
const onCancels = (e) => {
  IfdictItem(e) // 此处需要查询的原因是因为弹窗当中如果添加了一个空项然后取消后前端也被记录下来了、
  dictionarieShow.value = false
}

// 弹窗关闭
const onCloses = (e) => {
  IfdictItem(e) // 此处需要查询的原因是因为弹窗当中如果添加了一个空项然后取消后前端也被记录下来了、
  dictionarieShow.value = false
}

// 弹窗保存
const onConfirms = (e) => {
  dictionarieShow.value = false
  IfdictItem(e)
  Dictionaries()
}

// 生命周期
onActivated(() => {
  Dictionaries(true)
})
</script>

<template>
  <page-container class="container">
    <div class="box">
      <div class="left-view">
        <d-header
          :show-loading="false"
          :oper-buttons="operButtons"
          :search-rules="searchFromRules"
          :search-form-data="searchFromData"
          :search-form-items="searchFromItems"
          :search-buttons="serachButtons"
          :search-from-justify="'flexStart'"
          :search-from-full="true"
          @form-submit="onSubmit"
          @form-clear="onFormClear"
          @operation="onOperation"
        />
      </div>
      <div class="right-view">
        <d-table-promote
          style="width: 100%"
          :show-header="false"
          :table-data="tableData"
          :table-header-data="tableHeaderData"
          :page-config="pageConfig"
          :default-seleted="defualtSeleted"
          :show-index="true"
          :stripe="true"
          @row-click="onRowClick"
          @size-change="onSizeChange"
          @current-change="onCurrentChange"
        >
          <template #operation="scope">
            <operation
              :row="scope.row"
              :col="scope.item"
              @opertion-click="onErtion"
            />
          </template>
        </d-table-promote>
        <!-- <div class="line" /> -->
        <!-- <d-table-promote
          style="width: 34%"
          class="div-view"
          :show-loading="showLoading"
          :show-header="false"
          :stripe="true"
          :oper-buttons="[]"
          :search-form-items="[]"
          :search-buttons="[]"
          :table-data="rightTableData"
          :table-header-data="tableHeaderData2"
          :show-footer="false"
          :show-index="false"
        /> -->
      </div>
    </div>
  </page-container>
  <pop-up
    v-if="showDialog"
    :show-dialog="showDialog"
    :pop-data="popData"
    @cancel="onCancel"
    @close="onClose"
    @confirm="onConfirm"
  />
  <configure-dictionary
    v-if="dictionarieShow"
    :pop-id="ID"
    :dict-code="dictCode"
    :show-dialog="dictionarieShow"
    @cancel="onCancels"
    @close="onCloses"
    @confirm="onConfirms"
  />
</template>

<style scoped>
.right-view {
  flex: 1;
  display: flex;
  flex-flow: row wrap;
  justify-content: space-between;
}
.box {
  display: flex;
  flex-direction: column;
  flex: 1;
  height: 100%;
}
.line {
  width: 6px;
  height: 100%;
  background: #f2f2f2;
}
</style>
